有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用==

我有一个方法,它通过调用:resp.getResultCode()返回一个长对象数据类型。我想比较它HttpStatus.GONE.value(),它实际上只返回一个原始int值410。长unbox本身是否可以与int原语进行适当比较

if(resp.getResultCode() == HttpStatus.GONE.value()){
  // code inside..
}

共 (1) 个答案

  1. # 1 楼答案

    这是JLS explanation

    If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

    If the promoted type of the operands is int or long, then an integer equality test is performed.

    因此Long被解除绑定到long。并且对int应用数字提升,使其成为long。然后对它们进行比较

    考虑^ {< CD2>}将被“降级”到^ {< CD3>}的情况下,你会有这样的情况

    public static void main(String[] args) throws Exception {
        long lvalue = 1234567891011L;
        int ivalue = 1912277059;
        System.out.println(lvalue == ivalue); // false
        System.out.println((int) lvalue == ivalue); // true, but shouldn't
    }